package com.yc.txx.biz;

import com.yc.txx.entity.Lease;
import com.yc.txx.mapper.CarMapper;
import com.yc.txx.mapper.LeaseMapper;
import com.yc.txx.util.MyBatisHelper;
import org.apache.ibatis.session.SqlSession;

public class LeaseBiz {

    public void commit(Lease lease) throws BizExcpetion {
        if(lease.getDays().isEmpty()){
            throw new BizExcpetion("请选择用车时间");
        }
        try(final SqlSession session = MyBatisHelper.getSession(true)){
            final LeaseMapper mapper = session.getMapper(LeaseMapper.class);
            mapper.insert(lease);
        } catch (Exception e){
            throw new BizExcpetion( "订单提交失败,请联系客服!", e);
        }
    }

    // 提车
    public void out(String id, String cid) throws BizExcpetion {
        final SqlSession session = MyBatisHelper.getSession();
        try{
            final LeaseMapper leaseMapper = session.getMapper(LeaseMapper.class);
            final CarMapper carMapper = session.getMapper(CarMapper.class);
            leaseMapper.updateState("提车", id);
            carMapper.updateState("出库",cid);
            session.commit();
        } catch( Exception e){
            session.rollback();
            throw new BizExcpetion("业务繁忙, 稍后再试!", e);
        } finally {
            session.close();
        }
    }

    // 还车
    public void back(String id, String cid) throws BizExcpetion {
        final SqlSession session = MyBatisHelper.getSession();
        try{
            final LeaseMapper leaseMapper = session.getMapper(LeaseMapper.class);
            final CarMapper carMapper = session.getMapper(CarMapper.class);
            leaseMapper.updateState("还车", id);
            carMapper.updateState("在库",cid);
            session.commit();
        } catch( Exception e){
            session.rollback();
            throw new BizExcpetion("业务繁忙, 稍后再试!", e);
        } finally {
            session.close();
        }
    }
}
